import React, { useState, useImperativeHandle, useCallback } from "react"
import { DatePicker } from "antd-mobile"
import dayjs from "dayjs"

const PopupDate = (props, ref) => {
  const onSelect = props.onSelect
  const mode = props.mode
  const onVisable = props?.onVisable
  const [show, setShow] = useState(false) // 组件的显示和隐藏
  const [now, setNow] = useState(new Date())

  const labelRenderer = useCallback((type, data) => {
    switch (type) {
      case "year":
        return data + "年"
      case "month":
        return data + "月"
      case "day":
        return data + "日"
      case "hour":
        return data + "时"
      case "minute":
        return data + "分"
      case "second":
        return data + "秒"
      default:
        return data
    }
  }, [])

  const showP = () => {
    setShow(true)
  }
  const closeP = () => {
    setShow(false)
  }
  useImperativeHandle(ref, () => {
    return {
      showP,
      closeP,
    }
  })

  const choseMonth = (item) => {
    setNow(item)
    setShow(false)
    if (onVisable) {
      onVisable(show)
    }

    if (mode === "month") {
      onSelect(dayjs(item).format("YYYY-MM"))
    } else if (mode === "day") {
      onSelect(dayjs(item).format("YYYY-MM-DD"))
    }
  }

  return (
    <div>
      <DatePicker
        renderLabel={labelRenderer}
        title="时间选择"
        visible={show}
        precision={mode}
        onClose={() => {
          setShow(false)
          if (onVisable) {
            onVisable(show)
          }
        }}
        onConfirm={(val) => {
          choseMonth(val)
        }}
      />
    </div>
  )
}

PopupDate.displayName = "MyPopupDate"

export default React.forwardRef(PopupDate)
